package com.android.lovely.ui.dialog

import android.annotation.SuppressLint
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import androidx.core.text.buildSpannedString
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.lovely.R
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.aav.PreferentialManager.playEnter
import com.android.lovely.admob.Ad
import com.android.lovely.admob.showReword
import com.android.lovely.api.getRewardGemUseCase
import com.android.lovely.data.PayDetail
import com.android.lovely.databinding.DialogPayBinding
import com.android.lovely.databinding.DialogSignBinding
import com.android.lovely.databinding.ItemDialogPayBinding
import com.android.lovely.databinding.ItemPayBinding
import com.android.lovely.databinding.ItemPayProductBinding
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.manager.WorkStore
import com.android.lovely.ui.activity.PayAdAdapter
import com.android.lovely.ui.activity.PayFirstAdapter
import com.android.lovely.ui.activity.PayTitleAdapter
import com.android.lovely.ui.activity.ProductItemListAdapter
import com.android.lovely.ui.activity.ProductListAdapter
import com.android.lovely.ui.activity.RechargeBackActivity
import com.android.lovely.ui.fragment.HomeListItemDecoration
import com.android.lovely.ui.viewmodel.PayViewModel
import com.android.lovely.user.UserManager
import com.android.lovely.user.UserManager.registerAuthChange
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withTimeoutOrNull

/**
 *
 * @author why
 * @date 2025/3/25 22:16
 */
class PayDialog : BaseDialogFragment<DialogPayBinding>()  {

    private val viewModel by viewModels<PayViewModel>()

    private val concatAdapter =
        ConcatAdapter(ConcatAdapter.Config.Builder().setIsolateViewTypes(false).build())

    private val productListAdapter by lazy {
        ProductDialogListAdapter()
    }
    override fun initializeViews() {

        productListAdapter.onPay = {
            viewModel.pay(requireActivity(), it)
        }
        lifecycleScope.launchSafety {
            PreferentialManager.eventFlow.collectLatest {
                binding.preferential.isVisible = UserManager.isB()
                binding.preferential.playEnter()
            }
        }
        binding.preferential.clickable {
            PreferentialDialog().show(childFragmentManager)
        }
        binding.rv.layoutManager = LinearLayoutManager(requireActivity())
        binding.rv.adapter = concatAdapter
        binding.ivReport.clickable {
            startPage<RechargeBackActivity>()
        }
        concatAdapter.addAdapter(productListAdapter)

        binding.ivRefresh.clickable {
            lifecycleScope.launchWithLoading {
                UserManager.refreshAuthSync()
            }
        }
        registerAuthChange {
            binding.tvCount.text = it.point.toString()
        }
        if (Ad.WalletPage.getId().isNotEmpty()) {
            binding.layoutFree.isVisible = true
            setAdLayout()
        }
        binding.get.clickable {
            showPayAd()
        }

        lifecycleScope.launchSafety {
            viewModel.productFlow.collect {
                productListAdapter.updateList(arrayListOf(it.list))

            }
        }
        viewModel.requestProductList()
    }

    override fun isBottom(): Boolean {
        return true
    }

    @SuppressLint("SetTextI18n")
    private fun setAdLayout() {
        val max = UserManager.userInfo?.adNormalMaxNum ?: 0
        binding.get.text = getString(R.string.get_count, WorkStore.getInstance().buyDialogShowCount, max)
        binding.disable.isVisible = Ad.WalletDialog.enable().not()
    }

    private fun showPayAd() {
        lifecycleScope.launchWithLoading {
            withTimeoutOrNull(15000){
                Ad.WalletDialog.load()?.join()
            }
            requireActivity().showReword(Ad.WalletDialog) {
                if (it) {
                    lifecycleScope.launchWithLoading {
                        getRewardGemUseCase("normal").let {
                            UserManager.updateGems(it.getOrDefault("surplus", UserManager.userInfo?.point ?: 0))
                            showToast(getString(R.string.sign_success, (it.getOrDefault("point", 0)).toString()))
                        }
                        WorkStore.getInstance().buyDialogShowCount++
                        setAdLayout()
                    }.onError {
                        showToast(getString(R.string.ad_fail))
                    }
                } else {
                    showToast(getString(R.string.ad_fail))
                }
            }
        }
    }
}

class ProductDialogListAdapter : BaseAdapter<List<PayDetail>, ItemPayProductBinding>() {
    var onPay: ((PayDetail) -> Unit)? = null
    val adapter by lazy {
        ProductDialogItemListAdapter()
    }

    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: List<PayDetail>?,
        binding: ItemPayProductBinding,
        position: Int
    ) {
//        adapter.onPay = onPay
        binding.rvPay.layoutManager = GridLayoutManager(binding.root.context, 3)
        binding.rvPay.adapter = adapter
        binding.rvPay.addItemDecoration(HomeListItemDecoration(10.dp))
        adapter.updateList(item?: arrayListOf())
    }

    override fun getItemViewType(position: Int): Int {
        return 102
    }
}

class ProductDialogItemListAdapter : BaseAdapter<PayDetail, ItemDialogPayBinding>() {
    var onPay: ((PayDetail) -> Unit)? = null
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: PayDetail?,
        binding: ItemDialogPayBinding,
        position: Int
    ) {
        item ?: return
        binding.apply {
            tvCount.text = root.context.getString(R.string.first_pay_title, item?.point ?: "")
            count.text = root.context.getString(R.string.first_pay_money, item?.price.toString())
            tvOld.text = root.context.getString(R.string.first_pay_money, item?.oldPrice.toString())
            tvOld.paint.isStrikeThruText = true
            if (item.oldPrice > 0) {
                val spannedDayText = buildSpannedString {
                    val dayText = "${(((item.oldPrice - item.price) / item.oldPrice) * 100).toInt()}%"
                    // 先添加字体大小为 20 的部分
                    append(dayText)
                    setSpan(
                        AbsoluteSizeSpan(11, true),
                        0,
                        dayText.length,
                        SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    // 再添加一个空格
                    append(" ")
                    // 接着添加字体大小为 26 的部分
                    val extraText = root.context.resources.getString(
                        R.string.off,
                    )
                    val start = length
                    append(extraText)
                    setSpan(
                        AbsoluteSizeSpan(6, true),
                        start,
                        start + extraText.length,
                        SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
                tvReduction.text = spannedDayText
                tvReduction.isVisible = true
                tvOld.isVisible = true
            } else {
                tvReduction.isVisible = false
                tvOld.isVisible = false
            }

            binding.buy.clickable {
                item?.let { it1 -> onPay?.invoke(it1) }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return 103
    }

}